package com.game.packet;


import com.game.bean.Role;
import com.game.hot.Manager;
import com.game.util.LogUtil;
import com.nets.packet.AbstractPacket;
import com.nets.packet.Invoke;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

/**
 * @author sig
 * @since 2016/9/26
 */
public class Packet extends AbstractPacket {

    public Packet() {
    }

    public Packet(PacketType req) {
        setPacketType(req);
        put("mark", 1);
    }

    public Packet(PacketType req, int mark) {
        setPacketType(req);
        put("mark", mark);
    }

    public Packet(Packet req) {
        setPacketType(req.getPacketType());
        put("mark", 1);
    }

    public Packet(Packet req, int mark) {
        setPacketType(req.getPacketType());
        put("mark", mark);
    }

    @Override
    public void run() {
        try {
            Role role = null;
            PacketType type = (PacketType) getPacketType();

            if (type != PacketType.sendMd5 &&
                    type != PacketType.sendDic &&
                    type != PacketType.hotTest) {
                role = Manager.getRoleMg()
                        .getOnlineRole(getRoleIdKey());

                if (null == role) return;
            }
            Invoke invoke = type.getInvoke();

            if (null != invoke) invoke.invoke(role, this);
        } catch (Exception e) {
            LogUtil.console.error(e.getMessage(), e);
        }
    }

    public long getRoleIdKey() {
        AttributeKey<Long> key = AttributeKey.valueOf("roleId");
        Attribute<Long> attr = getChannel().attr(key);

        if (null != attr) return attr.get();
        return 0L;
    }

    public void setRoleIdKey(long roleId) {
        AttributeKey<Long> key = AttributeKey.valueOf("roleId");
        Attribute<Long> attr = getChannel().attr(key);
        attr.set(roleId);
    }
}
